package edu.byu.intex2.data.dao;

import edu.byu.intex2.data.Cache;
import edu.byu.intex2.data.ConnectionPool;
import edu.byu.intex2.data.DataException;
import edu.byu.intex2.data.bo.ConceptualCar;
import edu.byu.intex2.data.bo.Task;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Task Data Access Object
 * @author Jason Whiting
 */
public class TaskDAO
{

    /////////////////////////////////////////////
    ///   Singleton code
    private static TaskDAO instance = null;

    /** Creates a new instance of TaskDAO */
    private TaskDAO()
    {
    }//constructor

    /** Retrieves the single instance of this class */
    public static synchronized TaskDAO getInstance()
    {
        if (instance == null)
        {
            instance = new TaskDAO();
        }
        return instance;
    }//getInstance

    ////////////////////////////////////////////
    ///   CREATE methods
    /**
     * Creates a new task in the database */
    public Task create(String id) throws DataException
    {
        Task task = new Task(id);
        task.setObjectAlreadyInDB(false);
        Cache.getInstance().put(task.getId(), task);
        return task;
    }//create


    ////////////////////////////////////////////
    ///   READ methods
    /**
     * Reads an existing task from the database     */
    public Task read(String id) throws DataException
    {
        // Check Cache
        if (Cache.getInstance().containsKey(id))
        {
            return (Task) Cache.getInstance().get(id);
        }

        // Get Connection
        Connection conn = ConnectionPool.getInstance().get();

        // Try Reading with connection
        try
        {
            return read(id, conn);
        } catch (Exception e)
        {
            throw new DataException("An error occurred while reading the business object information.", e);
        } finally
        {
            ConnectionPool.getInstance().release(conn);
        }
    }

    /**
     * Internal method to read an existing task from the database
     * @return task
     */
    synchronized Task read(String id, Connection conn) throws Exception
    {
        // Check Cache
        if (Cache.getInstance().containsKey(id))
        {
            return (Task) Cache.getInstance().get(id);
        }

        // Prepare a SQL Statement
        PreparedStatement stmt = conn.prepareStatement("SELECT * FROM task where id=?");

        try
        {
            stmt.setString(1, id);
            ResultSet rs = stmt.executeQuery(); // execute query
            if (rs.next())
            {
                // Read the record with the result set
                return readRecord(rs, conn);
            }//if
            throw new DataException("Task with id '" + id + "' not found.");
        } finally
        {
            stmt.close();
        }
    }//read

    /** Internal method to create a task object from a record  */
    synchronized Task readRecord(ResultSet rs, Connection conn) throws Exception
    {
        if (Cache.getInstance().containsKey(rs.getString("id")))
        {
            return (Task) Cache.getInstance().get(rs.getString("id"));
        }
        // Create new task object
        Task task = new Task(rs.getString("id"));

        // Task is already in DB
        task.setObjectAlreadyInDB(true);

        // Put task in cache
        Cache.getInstance().put(task.getId(), task);

        // Set Task Attributes
        task.setDescription(rs.getString("description"));

        // Task is dirty and needs to be saved to DB
        task.setDirty(false);

        return task;
    }//readRecord


    /////////////////////////////////////////////
    ///   UPDATE methods
    /** Saves an existing task in the database */
    public void save(Task task) throws DataException
    {
        // get a connection from the pool, save all of the sales first using the other task method and then commit them in the database
        Connection conn = ConnectionPool.getInstance().get();

        try
        {
            save(task, conn); // save with connection
            conn.commit();  // commit the db transaction
        } catch (Exception e)
        {
            try
            {
                //rollback if there were any errors saving, catch any other errors you might have
                conn.rollback();
            } catch (SQLException e2)
            {
                throw new DataException("Could not roll back the task database transaction!", e2);
            }
            throw new DataException("An error occurred while saving the task object information.", e);
        } finally
        {
            // release the connection
            ConnectionPool.getInstance().release(conn);
        }
    }

    /** Internal method to update a task in the database */
    void save(Task task, Connection conn) throws Exception
    {
        // put the task object to cache
        Cache.getInstance().put(task.getId(), task);

        // decide whether to update or insert into the database
        if (task.isObjectAlreadyInDB() && task.isDirty())
        {
            update(task, conn);
        } else if (task.isDirty())
        {
            insert(task, conn);
        }//if
    }

    /** External method to update or create a task in the database without committing connection */
    public void saveNoCommit(Task task, Connection conn, Boolean alreadyInDB) throws Exception
    {
        // decide whether to update or insert into the database
        if (alreadyInDB)
        {
            update(task, conn);
        } else
        {
            insert(task, conn);
        }
    }

    /** Saves an existing task to the database */
    private void update(Task task, Connection conn) throws Exception
    {
        // use a prepared statement to prevent sql injection
        PreparedStatement stmt = conn.prepareStatement("UPDATE task SET description=?  WHERE id=?");
        try
        {
            // Get Task Attributes and add them to the statement
            stmt.setString(1, task.getDescription());
            stmt.setString(2, task.getId());
            stmt.execute();

            // Task is clean!
            task.setDirty(false);
        } finally
        {
            stmt.close();  // make sure to close the prepared statement
        }
    }

    /** Inserts a new task into the database */
    private void insert(Task task, Connection conn) throws Exception
    {
        PreparedStatement stmt = conn.prepareStatement("INSERT INTO task (id, description) VALUES (?, ?)");
        try
        {
            // Set Task Attributes
            stmt.setString(1, task.getId());
            stmt.setString(2, task.getDescription());
            stmt.execute();

            task.setObjectAlreadyInDB(true); // now in DB
            task.setDirty(false); // object is clean
        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            stmt.close(); // close the prepared statement
        }
    }

    /////////////////////////////////////////////////
    ///   DELETE methods
    /** We do not support deleting of business objects in this application */
    public void delete(Task task) throws DataException
    {
        throw new RuntimeException("Nice try. The delete function is not supported in this application.");
    }

    ////////////////////////////////////////////////
    ///   SEARCH methods
    /** Internal method to search by certain fields */
    private List<Task> search(PreparedStatement stmt, Connection conn) throws Exception
    {
        List<Task> tasks = new ArrayList<Task>();

        try
        {
            ResultSet rs = stmt.executeQuery();
            while (rs.next())
            {
                tasks.add(readRecord(rs, conn));
            }
        } finally
        {
            stmt.close();
            ConnectionPool.getInstance().release(conn);
        }

        return tasks;
    }

    /* Allow user to search by either first or last name or phone */
    public List<Task> getTasksByCC(ConceptualCar conceptualCar) throws Exception
    {
        //establish connection and prepared statement
        Connection conn = ConnectionPool.getInstance().get();
        PreparedStatement stmt = conn.prepareStatement("SELECT t.description, t.id FROM task t, task_cc WHERE t.id = task_cc.task_id AND task_cc.conceptual_car_id =? ");

        stmt.setString(1, conceptualCar.getId());
        return search(stmt, conn);
    }
}
